<template>
    <div id="newOrder">
        <div class="none" v-if="show" @click="addAddress">
            <span>+ 添加收货地址</span>
        </div>
        <div class="have" v-else @click="goAddress">
            <img src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/newOrder/address.png">
            <ul>
                <li>{{addressInfo.re_name}}<span>{{addressInfo.re_mobile}}</span></li>
                <li class="where">{{addressInfo.address_info.value[0]}}&nbsp;{{addressInfo.address_info.value[1]}}&nbsp;{{addressInfo.address_info.value[2]}}&nbsp;{{addressInfo.re_address}}</li>
            </ul>
            <img src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/newOrder/more@2x.png" style="width:.12rem;height:.24rem;float:right;margin-right:.24rem;">
        </div>
        <img src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/newOrder/rainbow.png" style="width:100%;">
        <div class="space" style="height:.2rem;background:#f6f6f6;"></div>
        <div class="shop">
            <ul class="shopping">
                <li class="headerImg"><img :src="headImg"></li>
                <li class="name">{{name}}</li>
            </ul>
        </div>
        <div class="cutDetail">
            <ul class="photo">
                <li><img :src="shopImg"></li>
            </ul>
            <ul class="cut-right">
                <li class="one" style="-webkit-box-orient: vertical;">{{title}}</li>
                <li class="two"><span>{{spec}}</span></li>
                <li class="three">
                    <!--<span class="icon" v-if="this.$route.query.tag!=1"></span>-->
                    <span class="money" v-if="this.$route.query.tag!=1" style="margin-right: .12rem;">¥{{price_min}}</span>
                    <span class="before" :style="this.$route.query.tag!=1?'text-decoration: line-through; font-size:.24rem; color:#969696':'font-size:.24rem; color:##323232'">¥{{price_max}}</span>
                </li>
            </ul>
        </div>
        <div class="yes">
            <ul class="one">
                <li>商品数量</li>
            </ul>
            <ul class="two">
                <li @click="reduceNum" v-if="this.$route.query.isCutZero==2||this.$route.query.iscut==1"><img src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/newOrder/Less.png" ></li>
                <li class="num">{{buy_num}}</li>
                <li @click="addNum" v-if="this.$route.query.isCutZero==2||this.$route.query.iscut==1"><img src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/newOrder/plus.png"></li>
            </ul>
        </div>
        <div class="yes">
            <span class="name">商品金额</span>
            <span class="add">¥{{price_max}}</span>
        </div>
        <div class="yes">
            <span class="name">{{delivery_price=='0'?'运费(包邮)':'运费'}}</span>
            <span class="add">{{delivery_price=='0'?'免运费':'￥'+delivery_price}}</span>
        </div>
        <div class="yes" v-if="showCut">
            <span class="name">砍价金额</span>
            <span class="add">-¥{{cutMoney}}</span>
        </div>
        <div class="yes" v-if="this.$route.query.isCutZero==2||this.$route.query.iscut==1">
            <span class="name">优惠券</span>
            <span class="add" :style="colorChange"  @click="goCoupon(isGo)"> {{showCouponText}}<img v-if="showImg" src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/more@2x.png" style="width: .14rem;height:.26rem;margin-left:.12rem;"></span>
        </div>
        <div class="yes">
            <span class="name">可用金额  <span style="color:#9948c3;">¥{{usedMoney | priceFixed}}</span></span>
            <span class="add"><img @click="changeImg" :src="flag==0?'https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/change/unselected_a.png':'https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/newOrder/checked_c.png' "style="width:.4rem;height:.4rem;"></span>
        </div>
        <div class="end">
            <span class="name">共<span>{{buy_num}}</span>件商品 总计 : ¥<span class="weight">{{total| priceFixed}}</span></span>
        </div>
        <div class="space" style="padding:.8rem;background:#f6f6f6;"></div>
        <div class="endto">
            <span class="start">总计 : <span class="icon">¥</span>
                <span class="new">{{total| priceFixed}}</span>
                <button class="btn" @click="submitOrder">{{ordermsg}}</button>
            </span>
        </div>
        <!--遮罩层-->
        <div class="templBg" v-if="showTem" @click="Bback"></div>
        <!--关闭符号-->
        <div class="styleX" v-if="showTem" @click="Bback">
            <img src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/change/close_b.png">
        </div>
        <!--一行字弹框-->
        <div class="newContext" v-if="test">
            <p>{{newContext}}</p>
        </div>
        <!--未关注弹框-->
        <div class="contexts"  v-if="guanzhu">
            <p>关注公众号,帮好友砍更多价格</p>
            <img class="imgLeft" :src="guanzhuInfo.codeUrl">
            <img class="imgRight" :src="guanzhuInfo.imgFinger">
        </div>
        <v-alert :style="newPosition" :context="context" v-if="showAlert"></v-alert>
    </div>

</template>
<script>
  import store from "../store/newStore.js";
  import config from "../config/config.js";
  import share from "../share/share.js";
  import Alert from "../alert.vue";
  import MtaH5 from 'mta-h5-analysis';
  export default {
    data(){
      return{
        show:true,
        addressInfo:[],
        super_id:'',
        headImg:'',
        name:'',
        buy_num:1,
        showCut:false,
        shopImg:'',
        price_max:'',
        title:'',
        subTitle:'',
        pro_price:'',
        spec:[],
        type:'',
        isCutZero:'',
        sku_id:'',
        money:'',
        usedMoney:'',
        cutid:'',
        iscut:'',
        cutMoney:Number,
        delivery_price:Number,
        addressOptions:'',
        isAddress:1,
        showCouponText:'使用优惠券',
        CouponMoney:0,
        isGo:Boolean,
        ordermsg:'提交订单',
        flag:0,
        id:null,
        context:'',
        showAlert:false,
        colorChange:{},
        showImg:false,
        newPosition:'position:fixed;top:15%;',
        payState:1,
        pushOrderedMonry:'',
        pushOrderedOrderId:'',
        showTem:false,
        guanzhu:false,
        test:false,
        guanzhuInfo:Object,
        newContext:'',
          c:''
      }
    },
    components:{
      "v-alert":Alert
    },
    methods:{
      Bback(){
        this. showTem = false;
        this.guanzhu = false;
        this.test = false;
      },
      changeImg(){
        if(this.flag == 0){
          this.flag = 1;

        }else{
          this.flag = 0
        };
      },
      addAddress(){
        this.$router.push('/addAddress/detailAddress');
      },
      GetCoupon(price){
        var value=JSON.stringify({"type":4,"price":price,"token":localStorage.getItem('token')}),
          key=demo(value);
        axios.post('/Home/Coupon/GetCoupon',{
          value:value,
          key:key,
          ticket:this.ticket
        },config)
          .then(function(response) {
            if(response.data.data==''){
              this.showCouponText='无可用优惠券';
              this.isGo=false;
              this.$store.commit('increment',response.data.ticket);
              this.colorChange = {'color':'#969696'};
              this.showImg = false;
            }else{
              if(localStorage.getItem('couponInfo')){
                var couponInfo=JSON.parse(localStorage.getItem('couponInfo'));
                this.showCouponText=-couponInfo.money;
                this.CouponMoney=couponInfo.money;
                this.id=couponInfo.id
              }else if(this.$route.path =='/address/1'){
                this.showCouponText='使用优惠券';
                this.id=null;
                this.colorChange = {'color':'#9948c3'};
                this.showImg = true;
              }else{
                this.showCouponText='使用优惠券';
                this.id=null;
                this.colorChange = {'color':'#9948c3'};
                this.showImg = true;
              }
              this.$store.commit('increment',response.data.ticket);
              this.isGo=true;
            }
          }.bind(this))
          .catch(function (error) {
            console.log(error);
          });
      },
      addNum(){
        this.buy_num++;
      },
      reduceNum(){
        if(this.buy_num==1){
               this.buy_num=1
             }else{
               this.buy_num--;
             }
      },
      goCoupon(isGo){
        if(isGo==true){
               this.$router.push('/Canusecoupon/'+(this.buy_num*this.price_max).toFixed(1))
             }
      },
      submitOrder(){
        var that = this;
        var type=this.type,
          sku_id=this.sku_id,
          source=3,
          buy_num=this.buy_num,
          address_id=this.super_id,
          cutid=this.cutid,
          coupon_id=this.id,
          iscut=this.iscut;
          this.isCutZero=this.$route.query.isCutZero;
          if(this.iscut==2){
            //alert(this.isCutZero);
            // alert(this.iscut);
              if(this.flag==0){
                  var value=JSON.stringify({"randomInfo":{'cut_money':this.price_max},"address_id":address_id,"buy_num":buy_num,"source":source,"sku_id":sku_id,"type":this.iscut,"cut_id":cutid,"coupon_id":coupon_id,"token":localStorage.getItem('token'),"cut_money":1}),
                      key=demo(value);
              }else{
                  var value=JSON.stringify({"randomInfo":{'cut_money':this.price_max},"address_id":address_id,"buy_num":buy_num,"source":source,"sku_id":sku_id,"type":this.iscut,"cut_id":cutid,"coupon_id":coupon_id,"money_ticket":this.money,"token":localStorage.getItem('token'),"cut_money":1}),
                      key=demo(value);
              }
          }else{
            // alert(this.iscut+'else');
            if(this.flag==0){
              var value=JSON.stringify({"address_id":address_id,"buy_num":buy_num,"source":source,"sku_id":sku_id,"type":this.iscut,"cut_id":cutid,"coupon_id":coupon_id,"token":localStorage.getItem('token')}),
                key=demo(value);
            }else{
              var value=JSON.stringify({"address_id":address_id,"buy_num":buy_num,"source":source,"sku_id":sku_id,"type":this.iscut,"cut_id":cutid,"coupon_id":coupon_id,"money_ticket":this.money,"token":localStorage.getItem('token')}),
                key=demo(value);
            }
          }
        if(address_id==''){
          var that=this;
          this.showAlert=true;
          this.context='请先添加收货地址';
          setTimeout(()=>{that.showAlert=false},2000)
        }else{
          axios.post('/Home/Order/PushOrder',{
            value:value,
            key:key,
            ticket:this.ticket
          },config)
            .then(function(response) {
              if(response.data.code==200){
                this.pushOrderedMonry=response.data.data.money;
                this.pushOrderedOrderId=response.data.data.orderId;
                if(response.data.data.money==0){
                  this.$store.commit('increment',response.data.ticket);
                  this.OrderPayZero(response.data.data.orderId);
                }else{
                  this.$store.commit('increment',response.data.ticket);
                  var values=JSON.stringify({"type":1,"money":response.data.data.money,"orderid":response.data.data.orderId,"token":localStorage.getItem('token')}),
                    keys=demo(values);
                  axios.post('/Home/Pay/OrderPay',{
                    value:values,
                    key:keys,
                    ticket:this.ticket
                  },config)
                    .then(function(res) {
                      if(res.data.code==200){
                        this.$store.commit('increment',res.data.ticket);
                        function jsApiCall()
                        {
                          WeixinJSBridge.invoke('getBrandWCPayRequest', {
                              "appId": res.data.data.appId,     //公众号名称，由商户传入
                              "timeStamp": res.data.data.timeStamp,//时间戳，自1970年以来的秒数
                              "nonceStr": res.data.data.nonceStr, //随机串
                              "package": res.data.data.package,
                              "signType":"MD5",         //微信签名方
                              "paySign": res.data.data.sign //微信签名
                            },
                            function(res){
                              WeixinJSBridge.log(res.err_msg);
                              if(res.err_msg == "get_brand_wcpay_request:ok"){
                                // if(this.$router.query.isCutZero==3){
                                //     alert(this.$router.query.isCutZero)
                                // }else{
                                //   that.$router.push('/success/'+response.data.data.orderId)
                                // }
                                that.GetPayResult();
                                // that.$router.push('/success/'+response.data.data.orderId)
                              }else{
                                that.ordermsg='继续支付';
                                //that.$router.push('/orderdetail/'+response.data.data.orderId+'/C')
                                that.$router.push({path:'/orderdetail/' + response.data.data.orderId + '/C',query:{
                                    'isCutZero':that.$route.query.isCutZero,
                                        'money':that.price_max
                                  }})
                              }
                            }
                          );
                        }
                        function callpay()
                        {
                          if (typeof WeixinJSBridge == "undefined"){
                            if( document.addEventListener ){
                              document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                            }else if (document.attachEvent){
                              document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                              document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                            }
                          }else{
                            jsApiCall();
                          }
                        }
                        callpay();
                      }else if(res.data.code==216){
                        this.showAlert=true;
                        this.context=res.data.msg;
                        setTimeout(()=>{that.showAlert=false},2000)
                      }else if(res.data.code==215){
                        this.showAlert=true;
                        this.context=res.data.msg;
                        setTimeout(()=>{that.showAlert=false},2000)
                      }

                    }.bind(this))
                    .catch(function (error) {
                      console.log(error);
                    });
                }
              }else if(response.data.code==201){
                this.showTem=true;
                this.guanzhu=true;
                this.guanzhuInfo=response.data.data;
              }else{
                this.newContext=response.data.msg;
                this.showTem=true;
                this.test=true;
              }
            }.bind(this))
            .catch(function (error) {
              console.log(error);
            });
          return false;
          if(this.payState==1){
          }else{
            if(this.pushOrderedMonry==0){
              this.OrderPayZero(this.pushOrderedMonry);
            }else{
              var values=JSON.stringify({"type":1,"money":this.pushOrderedMonry,"orderid":this.pushOrderedOrderId,"token":localStorage.getItem('token')}),
                keys=demo(values);
              axios.post('/Home/Pay/OrderPay',{
                value:values,
                key:keys,
                ticket:this.ticket
              },config)
                .then(function(res) {
                  if(res.data.code==200){
                    this.$store.commit('increment',res.data.ticket);
                    function jsApiCall()
                    {
                      WeixinJSBridge.invoke('getBrandWCPayRequest', {
                          "appId": res.data.data.appId,     //公众号名称，由商户传入
                          "timeStamp": res.data.data.timeStamp,//时间戳，自1970年以来的秒数
                          "nonceStr": res.data.data.nonceStr, //随机串
                          "package": res.data.data.package,
                          "signType":"MD5",         //微信签名方
                          "paySign": res.data.data.sign //微信签名
                        },
                        function(res){
                          WeixinJSBridge.log(res.err_msg);
                          if(res.err_msg == "get_brand_wcpay_request:ok"){
                            // that.$router.push('/success/'+response.data.data.orderId)；

                            that.GetPayResult();
                          }else{
                            that.ordermsg='继续支付';
                            that.payState=2;
                            window.location.href=location.href;
                          }
                        }
                      );
                    }
                    function callpay()
                    {
                      if (typeof WeixinJSBridge == "undefined"){
                        if( document.addEventListener ){
                          document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                        }else if (document.attachEvent){
                          document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                          document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                        }
                      }else{
                        jsApiCall();
                      }
                    }
                    callpay();
                  }else if(res.data.code==216){
                    this.showAlert=true;
                    this.context=res.data.msg;
                    setTimeout(()=>{that.showAlert=false},2000)
                  }else if(res.data.code==215){
                    this.showAlert=true;
                    this.context=res.data.msg;
                    setTimeout(()=>{that.showAlert=false},2000)
                  }
                }.bind(this))
                .catch(function (error) {
                  console.log(error);
                });
            }
          }
        }
      },
      GetPayResult(){
        var _self=this;
        var value=JSON.stringify({"orderid":_self.pushOrderedOrderId,"token":localStorage.getItem('token')}),
          key=demo(value);
        axios.post('/Home/pay/PayResult',{
          value:value,
          key:key,
          ticket:this.ticket
        },config)
          .then(function(response) {
            var that=this;
            if(response.data.data.shareid!==''){
                this.$router.push({
                    path:'/freeKan/' + response.data.data.shareid
                })
            }else {
              this.$router.push('/success/'+_self.pushOrderedOrderId)
            }
          }.bind(this))
          .catch(function (error) {
            console.log(error);
          });
      },
      GetPointInfo(){
        var value=JSON.stringify({"type":2,"token":localStorage.getItem('token')}),
          key=demo(value);
        axios.post('/Home/Address/GetPointInfo',{
          value:value,
          key:key,
          ticket:this.ticket
        },config)
          .then(function(response) {
            if(response.data.data==''){
              this.show=true;
              this.$store.commit('increment',response.data.ticket);
            }else{
              this.show=false;
              this.addressInfo=response.data.data;
              this.super_id=response.data.data.super_id;
              this.$store.commit('increment',response.data.ticket);
            }
            this.GetCoupon(this.total.toFixed(2))
          }.bind(this))
          .catch(function (error) {
            console.log(error);
          });
      },
      goAddress(){
        var that=this;
        var routeQuery=JSON.stringify(that.$route.query);
        localStorage.setItem("routeQuery",routeQuery);
          this.$router.push({
              path:'/address/'+this.isAddress,
            query:{
              isCutZero:this.$route.query.isCutZero
            }
          })
        localStorage.setItem("chooseAddress",1);
      },
      appointAddress(id){
        var value=JSON.stringify({"type":3,"id":id,"token":localStorage.getItem('token')}),
          key=demo(value);
        axios.post('/Home/Address/GetPointInfo',{
          value:value,
          key:key,
          ticket:this.ticket
        },config)
          .then(function(response) {
            if(response.data.data==''){
              this.show=true;
              this.$store.commit('increment',response.data.ticket);
            }else{
              this.show=false;
              this.addressInfo=response.data.data;
              this.super_id=response.data.data.super_id;
              this.$store.commit('increment',response.data.ticket);
            }
          }.bind(this))
          .catch(function (error) {
            console.log(error);
          });
      },
      OrderPayZero(orderid){
          var that=this;
        var values=JSON.stringify({"orderid":orderid,"token":localStorage.getItem('token')}),
          keys=demo(values);
        axios.post('Home/Pay/OrderPayZero',{
          value:values,
          key:keys,
          ticket:this.ticket
        },config)
          .then(function(res) {
            if(res.data.code==200){
              this.$store.commit('increment',res.data.ticket);
                that.GetPayResult();
            }
          }.bind(this))
          .catch(function (error) {
            console.log(error);
          });
      }
    },
    computed:{
      ticket(){
        return this.$store.state.getTicket;
      },
      total(){
        var that=this;
        if(this.flag==0){
          var totalPrice=this.buy_num*this.price_max-this.CouponMoney+Number(that.delivery_price)-that.cutMoney*that.buy_num;
          if(this.usedMoney!==this.money){
            this.usedMoney=this.money
          }
          return totalPrice;
        }else{
          var totalPrice=this.buy_num*this.price_max-this.CouponMoney+Number(that.delivery_price)-that.cutMoney*that.buy_num;
          if(this.money>=totalPrice){
            this.usedMoney=this.money-totalPrice;
            totalPrice=0;
          }else{
            totalPrice=totalPrice-this.usedMoney;
            this.usedMoney=0;
            return totalPrice
          }

          return totalPrice;
        }

      }
    },
    filters:{
      priceFixed:function(price){
        return parseFloat(price).toFixed(2)
      }
    },
    activated(){
      var that=this;
      this.flag=0;
      var value=JSON.stringify({"type":"1","token":localStorage.getItem('token')}),
        key=demo(value);
      axios.post('/Home/Login/MemberInfo',{
        value:value,
        key:key
      },config)
        .then(function(response) {
          this.$nextTick(function(){
            this.money=response.data.data.money;
            this.usedMoney=this.money;
          })
        }.bind(this))
        .catch(function (error) {
          console.log(error);
        });
      this.iscut=this.$route.query.iscut;
      this.headImg=this.$route.query.headImg;
      this.name=this.$route.query.name;
      this.shopImg=this.$route.query.shopImg;
      this.price_max=this.$route.query.price_max;
      this.price_min=this.$route.query.price_min;
      this.title=this.$route.query.title;
      this.spec=this.$route.query.spec;
      this.pro_price=this.$route.query.pro_price;
      this.sku_id=this.$route.query.sku_id;
      // this.isCutZero=this.$router.query.isCutZero;
      this.cutid=this.$route.query.cutid;
      this.delivery_price=this.$route.query.delivery_price;
      this.CouponMoney=0;
      that.ordermsg='提交订单';
      if(localStorage.getItem('choosed')){
        this.appointAddress(localStorage.getItem('choosed'))
      }else{
        setTimeout(function(){
          that.GetPointInfo();
        },500)
      }
      if(this.iscut==1){
        this.showCut=false;
      }else{
        this.showCut=true;
      }
      if(this.$route.query.cutMoney){
        this.cutMoney=this.$route.query.cutMoney
      }else{
        this.cutMoney=0
      }
      if(this.$store.state.getCutType==1){
        this.buy_num=1;
      }
      share({});
      MtaH5.init({
        "sid":'500594815',
        "cid":'500595819',
        "autoReport":0,
        "senseHash":0,
        "senseQuery":0,
        "performanceMonitor":0,
        "ignoreParams":[]
      });
      MtaH5.pgv();
    },
    deactivated(){
      this.super_id='';
      localStorage.removeItem('choosed');
      localStorage.removeItem('couponInfo');
    },
    mounted(){
      this.buy_num=this.$route.query.buy_num;
    },
    watch:{
      "buy_num":function(){
        var that=this;
        setTimeout(function(){
          that.GetPointInfo()
        },500)
      }
    }
  }
</script>

<style>

</style>